package main

import (
	"context"
	"flag"
	"fmt"
	"github.com/olivere/elastic/v7"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"month/models"

	"month/rpc/internal/config"
	"month/rpc/internal/server"
	"month/rpc/internal/svc"
	"month/rpc/month"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/service"
	"github.com/zeromicro/go-zero/zrpc"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
)

var configFile = flag.String("f", "etc/month.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)
	ctx := svc.NewServiceContext(c)

	s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
		month.RegisterMonthServer(grpcServer, server.NewMonthServer(ctx))

		if c.Mode == service.DevMode || c.Mode == service.TestMode {
			reflection.Register(grpcServer)
		}
	})
	defer s.Stop()

	fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
	s.Start()
}

// 同步数据
func Tong() {
	db, err := gorm.Open(mysql.Open("root:q025l6263@tcp(43.143.123.142:3306)/2107a"), &gorm.Config{})
	if err != nil {
		return
	}
	var f []models.Fgit
	err = db.Raw("select * from `fgit`").Scan(&f).Error
	if err != nil {
		return
	}

	esClient, err := elastic.NewClient(elastic.SetURL("http://43.143.123.142:9200"), elastic.SetSniff(false))
	if err != nil {
		return
	}

	for _, v := range f {
		_, err = esClient.Index().Index("fgit").Id(string(v.Id)).BodyJson(v).Do(context.Background())
		if err != nil {
			return
		}
	}
}
